from shutil import rmtree, copyfile
from os import sep, mkdir, remove
from os.path import exists, isfile, isdir
from time import localtime, strftime
from urllib import urlopen, urlretrieve
import tarfile, json

__copyright__ = "SnohomaNET, 2010 - www.snohoma.net"
__license__ = "GPLv2"

## String ##
def AddSep(s):
	if not s.endswith(sep):
		s += sep
	return s

def AddWebSep(s):
	if not s.endswith("/"):
		s += "/"
	return s

def rmExt(s, ext):
	if s.endswith(ext):
		return s.rstrip(ext)
	else:
		return s

def generate_manifest_path(app):
	return "data/%s/%s.manifest" % (app, app)
	
## OS ##
def check_path(f):
	return exists(f)

def mk_dir(p):
	if exists(p):
		return (False, "Directory already exists: %s" % p)
	try:
		mkdir(p)
		return (True, "Directory created: %s" % p)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)
		
def rm_dir(p):
	if not exists(p):
		return (False, "Directory does not exist: %s" % p)
	try:
		rmtree(p)
		return (True, "Directory removed: %s" % p)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)

def rm_file(f):
	if not exists(f):
		return (False, "File does not exist: %s" % f)
	try:
		remove(f)
		return (True, "File removed: %s" % f)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)

def copy_file(src, dest):
	try:
		copyfile(src, dst)
		return (True, "File copied.")
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)
	
def rm(p):
	if not exists(p):
		return (False, "Path not found: %s" % p)
	if isdir(p):
		r = rm_dir(p)
		if not r[0]:
			return (False, r[1])
		return (True, r[1])
	if isfile(p):
		r = rm_file(p)
		if not r[0]:
			return (False, r[1])
		return (True, r[1])
	return (False, "Unknown object type: %s" % p)
	
	
## JSON ##
def loadjson(f):
	try:
		f = open(f, "rb")
		r = json.load(f)
		f.close()
		return (True, r)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)
	except ValueError, e:
		return (False, e.strerror)

def savejson(f, d):
	try:
		f = open(f, "wb")
		json.dump(d, f, indent=4)
		f.close()
		return (True, d)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)
	except ValueError, e:
		return (False, e.strerror)

def load_pkg_manifest(pkg, m_path, format="gz"):
	try:
		t = tarfile.open(pkg, "r:" + format)
		manifest = json.load(t.extractfile(m_path))
		t.close()
		return (True, manifest)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)
	except ValueError, e:
		return (False, e.strerror)
	
def print_json(data):
	return json.dumps(data, indent=4)
	
def load_manifest(d, app):
	return loadjson(AddSep(d) + AddSep(app) + app + ".manifest")
	
def save_manifest(d, app, data=False):
	return savejson(AddSep(d) + AddSep(app) + app + ".manifest", data)

## Time/Date ##	
def datestamp(format="%m/%d/%Y"):
	return strftime(format, localtime())
	
def timestamp(format="%m/%d/%Y %H:%M:%S"):
	return strftime(format, localtime())

## Tarfile ##
def unpack(src, pkg, ext, path=".", format="gz"):
	try:
		t = tarfile.open(AddSep(src) + pkg + ext, "r:" + format)
		t.extractall(path=AddSep(path))
		t.close()
		return (True, "Package Extracted.")
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)

def pack(files, app, ext, dest, format="gz"):
	# files = list of files to include, run excludes previous to calling pack.
	try:
		t = tarfile.open(AddSep(dest) + app + ext, "w:" + format)
		rtn = { "included" : [], "excluded" : [] }
		for i in files:
			if exists(i):
				t.add(i)
				rtn["included"].append(i)
			else:
				rtn["excluded"].append(i)
		t.close()
		return (True, "Package created!", rtn)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)

## Web-based ##
def loadwebjson(url):
	try:
		u = json.load(urlopen(url))
		return (True, u)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)

def download_pkg(url, dest):
	try:
		u = urlretrieve(url, dest)
		return (True, u)
	except OSError, e:
		return (False, e.strerror)
	except IOError, e:
		return (False, e.strerror)

